package com.cooba.activitys.user;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.cooba.R;
import com.cooba.bean.UserInfoBean;
import com.cooba.dialog.DatePickerDialog;
import com.cooba.dialog.SelectPhotoDialog;
import com.cooba.utils.Constants;
import com.cooba.utils.FileOpeartionUtil;
import com.cooba.utils.InternalStorageContentProvider;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.cooba.views.CircleImageView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;

import eu.janmuller.android.simplecropimage.CropImage;

/**
 * Created by Administrator on 2015/12/16.
 * 用户信息
 */
public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int REQUEST_CODE = 0;
    private TextView mChangename, mGet_changenumber;
    private EditText mEt_changename;
    private ImageView mLoginimage_back;
    private RelativeLayout mChangPassword;
    private FrameLayout photo_fl;
    private ToggleButton tb_sex;
    private CircleImageView user_img;
    private File mCurImageFile;
    private InputMethodManager imm;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String login_id;
    private UserInfoBean userinfobean;
    private BitmapUtils bitmapUtils;
    private TextView changeBirthday;
    private String sex;//男0女1
    private String uuid;

    public static final int REQUEST_CODE_GALLERY = 1;
    public static final int REQUEST_CODE_TAKE_PICTURE = 2;
    public static final int REQUEST_CODE_CROP_IMAGE = 3;
    private File mFileTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        PushAgent.getInstance(this).onAppStart();

        photo_fl = (FrameLayout) findViewById(R.id.photo);
        user_img = (CircleImageView) findViewById(R.id.user_img);
        mChangename = (TextView) findViewById(R.id.changename);
        mLoginimage_back = (ImageView) findViewById(R.id.loginimage_back);
        mGet_changenumber = (TextView) findViewById(R.id.get_changenumber);
        mEt_changename = (EditText) findViewById(R.id.et_changename);
        mChangPassword = (RelativeLayout) findViewById(R.id.changPassword);
        tb_sex = (ToggleButton) findViewById(R.id.tb_sex);
        changeBirthday = (TextView) findViewById(R.id.changeBirthday);
        photo_fl.setOnClickListener(this);
        mChangename.setOnClickListener(this);
        mLoginimage_back.setOnClickListener(this);
        mGet_changenumber.setOnClickListener(this);
        mChangPassword.setOnClickListener(this);
        mEt_changename.setOnClickListener(this);
        changeBirthday.setOnClickListener(this);
        tb_sex.setOnClickListener(this);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        bitmapUtils = new BitmapUtils(UserInfoActivity.this);

        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mFileTemp = new File(Environment.getExternalStorageDirectory(),
                    FileOpeartionUtil.TEMP_PHOTO_FILE_NAME);
        } else {
            mFileTemp = new File(getFilesDir(),
                    FileOpeartionUtil.TEMP_PHOTO_FILE_NAME);
        }

        initData();
    }

    private void initData() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        if (!TextUtils.isEmpty(login_id)) {
            params.addBodyParameter("login_id", login_id);
        }
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.GetUserInfo, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                try {
                    userinfobean = new Gson().fromJson(responseInfo.result, UserInfoBean.class);
                    setUserInfo();
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setUserInfo() {
        if (userinfobean.getPhoto() != null) {
            bitmapUtils.display(user_img, userinfobean.getPhoto());
        } else {

        }

        mChangename.setText(TextUtils.isEmpty(userinfobean.getName()) ? "未设置" : userinfobean.getName());
        if (Utils.isnumber(userinfobean.getLogin_id())) {
            mGet_changenumber.setText(userinfobean.getLogin_id());
        } else {
            mGet_changenumber.setText("未绑定");
        }
        changeBirthday.setText(TextUtils.isEmpty(userinfobean.getBirthday()) ? "未设置" : userinfobean.getBirthday().substring(0, 10));
        if (userinfobean.getSex() != null) {
            if (userinfobean.getSex().equals("0")) {
                tb_sex.setChecked(false);
            } else {
                tb_sex.setChecked(true);
            }
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        switch (v.getId()) {
            case R.id.photo:
                showSelectPhotoDialog();
                break;
            case R.id.changename:
//                if (!Utils.isnumber(login_id)) {
//                    Toast.makeText(this, "未绑定手机号", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                final String name1 = mChangename.getText().toString();
                mEt_changename.setVisibility(View.VISIBLE);
                mChangename.setVisibility(View.GONE);
                mEt_changename.setFocusable(true);
                mEt_changename.setFocusableInTouchMode(true);
                mEt_changename.requestFocus();
                imm.showSoftInput(mEt_changename, InputMethodManager.SHOW_IMPLICIT);
                mEt_changename.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {

                        } else {
                            String name = mEt_changename.getText().toString().trim();
                            mChangename.setText(name);
                            mEt_changename.setVisibility(View.GONE);
                            mChangename.setVisibility(View.VISIBLE);
                            if (!name1.equals(name)) {
                                updateInfo("name", name);
                            }
                        }
                    }
                });

                break;
            case R.id.loginimage_back:
                finish();
                break;
            //修改密码
            case R.id.changPassword:
                if (!Utils.isnumber(login_id)) {
                    Toast.makeText(this, "未绑定手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                intent = new Intent(getApplication(), ChangPasswordActivity.class);
                startActivity(intent);
                //finish();
                break;
            //修改性别
            case R.id.tb_sex:
//                if (!Utils.isnumber(login_id)) {
//                    Toast.makeText(this, "未绑定手机号", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                if (tb_sex.isChecked()) {
                    sex = "1";
                } else {
                    sex = "0";
                }
                updateInfo("sex", sex);
                break;
            case R.id.get_changenumber:
                intent = new Intent(UserInfoActivity.this, ChangNumberActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;

            case R.id.changeBirthday:
//                if (!Utils.isnumber(login_id)) {
//                    Toast.makeText(this, "未绑定手机号", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                Calendar c = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(UserInfoActivity.this,
                        0, R.layout.date_picker_dialog, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        changeBirthday.setText("" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                        updateInfo("birthday", "" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                });

                dialog.setCanceledOnTouchOutside(true);
                android.view.Window window = dialog.getWindow();
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                window.setAttributes(lp);
                window.setBackgroundDrawableResource(android.R.color.transparent);
                window.setGravity(Gravity.BOTTOM);
                dialog.show();
                break;
            default:
                break;
        }
    }

    private void showSelectPhotoDialog() {
        final SelectPhotoDialog dialog = new SelectPhotoDialog(this);
        dialog.setNegativeButton(null);
        dialog.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.user_info_setting_dialog_select_photo_btn_takePicture:
                        takePicture();
                        dialog.dismiss();
                        break;
                    case R.id.user_info_setting_dialog_select_photo_btn_fromGallery:
                        openGallery();
                        dialog.dismiss();
                        break;
                    default:
                        break;
                }
            }

        });
        dialog.show();
    }

    private void openGallery() {

        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
    }

    private void takePicture() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        try {
            Uri mImageCaptureUri = null;
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                mImageCaptureUri = Uri.fromFile(mFileTemp);
            } else {

                mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
            }
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                    mImageCaptureUri);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
        } catch (ActivityNotFoundException e) {

            Log.d("wei", "cannot take picture", e);
        }
    }

    public static void copyStream(InputStream input, OutputStream output)
            throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }

    private void startCropImage() {

        Intent intent = new Intent(this, CropImage.class);
        intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath());
        intent.putExtra(CropImage.SCALE, true);

        intent.putExtra(CropImage.ASPECT_X, 2);
        intent.putExtra(CropImage.ASPECT_Y, 2);

        startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE) {
            String phoneNumber = data.getStringExtra("phone");
            if (phoneNumber != null) {
                Log.d("wei--", phoneNumber);
                mGet_changenumber.setText(phoneNumber);
            }
        }

        Bitmap bitmap;

        switch (requestCode) {
            case REQUEST_CODE_GALLERY:

                try {

                    InputStream inputStream = getContentResolver().openInputStream(
                            data.getData());
                    FileOutputStream fileOutputStream = new FileOutputStream(
                            mFileTemp);
                    copyStream(inputStream, fileOutputStream);
                    fileOutputStream.close();
                    inputStream.close();

                    startCropImage();

                } catch (Exception e) {

                    Log.e("wei", "Error while creating temp file", e);
                }

                break;
            case REQUEST_CODE_TAKE_PICTURE:

                startCropImage();
                break;
            case REQUEST_CODE_CROP_IMAGE:

                String path = data.getStringExtra(CropImage.IMAGE_PATH);
                if (path == null) {

                    return;
                }

                bitmap = BitmapFactory.decodeFile(mFileTemp.getPath());
                Log.d("wei", mFileTemp.getAbsolutePath());
                user_img.setImageBitmap(bitmap);
                //bitmapUtils.display(user_img, "file://" + mFileTemp.getAbsolutePath());
//                ImageLoader.getInstance().displayImage(, user_info_layout_user_image, Utils.getCircleDisplayOpt(false));
//			user_info_layout_user_image.setImageBitmap(bitmap);//.setBitmapImage(bitmap);


//			OutputStream outputStream = null;
//			try {
//				outputStream = getContentResolver().openOutputStream(
//						Uri.fromFile(new File(path)));
//
//				if (outputStream != null) {
//					bitmap.compress(Bitmap.CompressFormat.JPEG, 90,
//							outputStream);
//				}
//
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} finally {
//				try {
//					if (outputStream != null)
//						outputStream.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
                updatePhoto();


                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //更新用户信息
    private void updateInfo(String key, String value) {
        login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("login_id", login_id);
        params.addBodyParameter(key, value);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.UpdateUserInfo, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                Intent intent = new Intent();
                intent.setAction(Constants.UPDATE_DATA);
                sendBroadcast(intent);
            }
        });
    }

    private void updatePhoto() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("login_id", login_id);
        params.addBodyParameter("photo", mFileTemp);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.UploadPhoto, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取成功" + responseInfo.result);
                Intent intent = new Intent();
                intent.setAction(Constants.UPDATE_DATA);
                sendBroadcast(intent);
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        imm.hideSoftInputFromWindow(mEt_changename.getWindowToken(), 0);
        if (mEt_changename.getText().length() > 0) {
            mEt_changename.clearFocus();
        }
        return super.onTouchEvent(event);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
